package com.biz.datascope;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.Setter;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.Map;

/**
 * @author LXY
 * @Description 自定义sql 处理
 * @create 2025/06/28
 */
public class DataScopeInnerInterceptor implements InnerInterceptor {

    @Setter
    private DataScopeHandle dataScopeHandle;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
                            ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        // InnerInterceptor.super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
        // 获取未处理的原始 SQL 语句（含 ? 占位符）
        String originalSql = boundSql.getSql();
        // 获取 SQL 绑定的参数对象，可用于动态参数替换或条件追加
        Object parameterObject = boundSql.getParameterObject();
        // 查找参数中包含DataScope类型的参数
        DataScope dataScope = findDataScopeObject(parameterObject);
        if (dataScope == null) {
            return;
        }
        String scopeName = dataScope.getScopeName();
        String scopeContext = dataScope.getScopeContext();
        // 优先获取赋值数据
        if (StrUtil.isBlank(scopeContext) && dataScopeHandle.calcScope(scopeContext)) {
            originalSql = String.format("SELECT %s FROM (%s) temp_data_scope", dataScope.getFunc().getType(),
                originalSql);
            mpBs.sql(originalSql);
            return;
        }
        if (scopeContext.isEmpty()) {
            originalSql = String.format("SELECT %s FROM (%s) temp_data_scope WHERE 1 = 2",
                dataScope.getFunc().getType(), originalSql);
        }
        else {
            originalSql = String.format("SELECT %s FROM (%s) temp_data_scope WHERE temp_data_scope.%s %s",
                dataScope.getFunc().getType(), originalSql, scopeName, scopeContext);
        }

        mpBs.sql(originalSql);

    }

    /**
     * 查找参数是否包括DataScope对象
     * @param parameterObj 参数列表
     * @return DataScope
     */
    private DataScope findDataScopeObject(Object parameterObj) {
        if (parameterObj instanceof DataScope) {
            return (DataScope) parameterObj;
        }
        else if (parameterObj instanceof Map) {
            for (Object val : ((Map<?, ?>) parameterObj).values()) {
                if (val instanceof DataScope) {
                    return (DataScope) val;
                }
            }
        }
        return null;
    }
}
